package com.xbongbong.pro.message.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.message.domain.entity.PushSetEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.wrap.Entity;
import com.xbongbong.pro.message.constant.MessageSetDetailTitleConstants;
import com.xbongbong.pro.message.enums.PushObjectTypeEnum;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.pojo.MessageSetDetailPojo;
import com.xbongbong.pro.message.pojo.dto.MessageSetDetailDTO;
import com.xbongbong.pro.message.pojo.vo.MessageSetDetailVO;
import com.xbongbong.pro.message.pojo.vo.PushSetVO;
import com.xbongbong.pro.message.pushset.CluePushSet;
import com.xbongbong.saas.domain.entity.ext.ClueEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.ClueUserModel;
import com.xbongbong.sys.domain.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 市场管理消息推送设置实现类
 *
 * @author LiZhikang
 * @date 2022/11/5 16:37
 */
@Service
@Slf4j
public class MarketManagementMessageSetServiceImpl extends AbstractMessageSetService {

    @Resource
    private CommonHelp commonHelp;

    @Resource
    private ClueUserModel clueUserModel;

    @Override
    public List<String> alias() {
        return Collections.singletonList(XbbRefTypeEnum.MARKET_MANAGEMENT.getAlias());
    }

    @Override
    public String initSetDetailList() throws Exception {
        return null;
    }

    @Override
    public MessageSetDetailVO getSetDetailList(MessageSetDetailDTO messageSetDetailDTO) throws Exception {
        List<MessageSetDetailPojo> messageSetDetailPojos = new ArrayList<>();
        Integer typeInt = messageSetDetailDTO.getSaasIds().get(0).intValue();
        typeInt = XbbRefTypeEnum.transferBusinessType4Distributor(typeInt, messageSetDetailDTO.getDistributorMark());
        String alias = PushTypeEnum.getByCode(typeInt).getAlias();
        if (!Objects.equals(alias, PushTypeEnum.UNKNOWN.getAlias())) {
            String methodName = "getMessageSetSaas" + alias.substring(0, 1).toUpperCase() + alias.substring(1) + "DetailList";
            Method method = this.getClass().getDeclaredMethod(methodName, String.class, List.class, Integer.class);
            method.invoke(this, messageSetDetailDTO.getCorpid(), messageSetDetailPojos, typeInt);
        }
        return new MessageSetDetailVO(messageSetDetailPojos);
    }

    /**
     * 线索 8000
     *
     * @param corpid
     * @param messageSetDetailPojos
     * @param typeInt
     * @throws IllegalAccessException
     * @throws XbbException
     * @throws InstantiationException
     */
    private void getMessageSetSaasCluePushDetailList(String corpid, List<MessageSetDetailPojo> messageSetDetailPojos, Integer typeInt) throws IllegalAccessException, XbbException, InstantiationException {
        List<PushTypeEnum> pushTypeEnumList = new ArrayList<>(PushTypeEnum.getAllEnumByType(typeInt));
        List<PushTypeEnum> baseTypeEnum = new ArrayList<>();
        List<PushTypeEnum> otherTypeEnum = new ArrayList<>();
        boolean isCluePublicSeniorModel = commonHelp.isCluePublicPoolSeniorModel(corpid);
        for (PushTypeEnum pushTypeEnum : pushTypeEnumList) {
            Integer subCode = pushTypeEnum.getSubCode();
            boolean transferPush = isCluePublicSeniorModel && Objects.equals(subCode, PushTypeEnum.CLUE_TRANSFER_PUBLIC.getSubCode());
            if (Objects.equals(subCode, PushTypeEnum.CLUE_ADD_PUSH.getSubCode()) || Objects.equals(subCode, PushTypeEnum.CLUE_CHANGE_PUSH.getSubCode()) || Objects.equals(subCode, PushTypeEnum.CLUE_BACK_PUBLIC.getSubCode()) || transferPush) {
                baseTypeEnum.add(pushTypeEnum);
            }
            if (Objects.equals(subCode, PushTypeEnum.CLUE_HANDOVER_PUSH.getSubCode()) || Objects.equals(subCode, PushTypeEnum.CLUE_DISTRIBUTION_PUSH.getSubCode()) || Objects.equals(subCode, PushTypeEnum.CLUE_TEAM_ADD_DEL_MAIN.getSubCode()) || Objects.equals(subCode, PushTypeEnum.CLUE_TEAM_ADD_DEL_SYNERGETIC.getSubCode())) {
                otherTypeEnum.add(pushTypeEnum);
            }
        }

        CluePushSet cluePushSet = new CluePushSet();
        MessageSetDetailPojo baseDetail = new MessageSetDetailPojo();
        baseDetail.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.CLUE_BASE));

        List<PushSetEntity> basePushTypeList = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : baseTypeEnum) {
            PushSetEntity pushSetEntity = cluePushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            basePushTypeList.add(pushSetEntity);
        }
        List<PushSetVO> basePushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(basePushTypeList, basePushSetVOList, PushSetVO.class);
        baseDetail.setValue(basePushSetVOList);

        messageSetDetailPojos.add(baseDetail);

        MessageSetDetailPojo otherDetail = new MessageSetDetailPojo();
        otherDetail.setTitle(I18nMessageUtil.getMessage(MessageSetDetailTitleConstants.CLUE_FOLLOW));
        List<PushSetEntity> otherPushTypeList = new ArrayList<>();
        for (PushTypeEnum pushTypeEnum : otherTypeEnum) {
            PushSetEntity pushSetEntity = cluePushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            otherPushTypeList.add(pushSetEntity);
        }
        List<PushSetVO> otherPushSetVOList = new ArrayList<>();
        BeanUtil.copyPropertiesList(otherPushTypeList, otherPushSetVOList, PushSetVO.class);
        otherDetail.setValue(otherPushSetVOList);

        messageSetDetailPojos.add(otherDetail);
    }


    @Override
    public List<String> getUserIdListByPushSetRule(String corpid, Integer type, Integer subType, UserEntity userEntity, Entity entity) {
         return distinct(getClueUserIdList(corpid, subType, userEntity, entity));
    }

    private List<String> getClueUserIdList(String corpid, Integer subType, UserEntity userEntity, Entity entity) {
        String pushObjectString;
        Set<String> userIdList = new HashSet<>();
        ClueEntityExt clueEntityExt = (ClueEntityExt) entity;
        Long clueId = clueEntityExt.getId();
        CluePushSet cluePushSet = new CluePushSet();
        PushSetEntity pushSetEntity = cluePushSet.getPushSet(corpid, subType, pushSetModel);

        if (Objects.equals(pushSetEntity.getEnable(), 1)) {
            pushObjectString = pushSetEntity.getPushObject();
            JSONObject pushObject = JsonHelperUtil.parseObject(pushObjectString);
            String typeString = pushObject.getString("type");
            if (clueId != null && clueId > 0) {
                JSONArray typeJsonArray = JsonHelperUtil.parseArray(typeString);
                for (Object object : typeJsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    Integer enable = jsonObject.getInteger("enable");
                    if (Objects.equals(enable, 1)) {
                        String alias = jsonObject.getString("alias");
                        if (Objects.equals(alias, PushObjectTypeEnum.MAINUSER.getAlias())) {
                            userIdList.addAll(clueUserModel.getClueUserIds(corpid, Collections.singletonList(clueId), 1));
                            if(CollectionUtils.isEmpty(userIdList)){
                                log.warn("com.xbongbong.pro.message.help.PushHelper.getClueUserIdList userIdList is empty。corpid:{},cluid:{}",corpid,clueId);
                            }
                        }
                        if (Objects.equals(alias, PushObjectTypeEnum.COLLABORATOR.getAlias())) {
                            userIdList.addAll(clueUserModel.getClueUserIds(corpid, Collections.singletonList(clueId), 0));
                        }
                    }
                }
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(userIdList), DateUtil.getInt());
            } else {
                return getPushUserIdList(userEntity, pushObjectString, new ArrayList<>(userIdList), DateUtil.getInt());
            }
        } else {
            return new ArrayList<>();
        }
    }
}
